class PaymentManager {
    constructor() {
      this.app = getApp();
    }
  
    validatePaymentPrerequisites() {
      if (!this.app.globalData.userInfo) {
        return { valid: false, message: '请先登录' };
      }
      if (!this.app.globalData.userInfo.phone) {
        return { valid: false, message: '请先绑定手机号' };
      }
      return { valid: true };
    }
  
    async handlePayment(orderNo, documents) {
      try {
        await this._uploadAllDocuments(orderNo, documents);
        const paymentParams = await this._getPaymentParams(orderNo);
        await this._requestPayment(paymentParams);
        return { success: true };
      } catch (error) {
        return { success: false, error: error.message || '支付失败' };
      }
    }
  
    async _uploadAllDocuments(orderNo, { electronicDocuments, paperDocuments }) {
      const uploadPromises = [];
  
      electronicDocuments.forEach(doc => {
        if (doc.status === '已完成') {
          const imageFields = doc.fields.filter(field => field.type === 'image');
          imageFields.forEach(field => {
            const filePath = doc.formData?.[field.name];
            if (filePath) {
              uploadPromises.push(this._uploadFile(filePath, {
                type: doc.name,
                fieldName: field.name,
                orderId: orderNo
              }));
            }
          });
          uploadPromises.push(this._submitFormData({ ...doc, orderId: orderNo }));
        }
      });
  
      paperDocuments.forEach(doc => {
        if (doc.status === '已完成') {
          uploadPromises.push(this._submitFormData({ ...doc, orderId: orderNo }));
        }
      });
  
      return Promise.all(uploadPromises);
    }
  
    async _uploadFile(filePath, { type, fieldName, orderId }) {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/file/upload',
          filePath,
          name: 'file',
          formData: { type, fieldName, orderId },
          header: { 'token': wx.getStorageSync('token') },
          success: resolve,
          fail: reject
        });
      });
    }
  
    async _submitFormData(doc) {
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/form/submit',
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: {
            orderId: doc.orderId,
            materialType: doc.name,
            formData: doc.formData
          },
          success: (res) => {
            if (res.data.code === 1) resolve(res.data);
            else reject(new Error(res.data.msg || '表单提交失败'));
          },
          fail: reject
        });
      });
    }
  
    _getPaymentParams(orderNo) {
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/pay/payment',
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: {
            orderId: orderNo,
            userId: this.app.globalData.userInfo.id
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 1) resolve(res.data.data);
            else reject(new Error(res.data.msg || '获取支付参数失败'));
          },
          fail: reject
        });
      });
    }
  
    _requestPayment(payData) {
      return new Promise((resolve, reject) => {
        wx.requestPayment({
          ...payData,
          success: resolve,
          fail: reject
        });
      });
    }
  }
  
  export default PaymentManager;